package com.dhcc.DRGsHosp.application.impl;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Named;

import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.dayatang.querychannel.QueryChannelService;
import org.openkoala.koalacommons.resourceloader.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.dhcc.DRGsHosp.application.DRGsApplication;
import com.dhcc.DRGsHosp.core.domain.DRGs;
import com.dhcc.DRGsHosp.core.domain.IndexCal;
import com.dhcc.DRGsHosp.infra.util.MonitorResultUtil;

@Named
@Transactional
public class DRGsApplicationImpl implements DRGsApplication,Serializable {
	private static final long serialVersionUID = 1L;
	@Autowired
	private JdbcTemplateObj jdbcTemplateObj;
	
	private QueryChannelService queryChannel;

    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
    
	public DRGs getDRGs(String drgCode) {
		return DRGs.get(DRGs.class, drgCode);
	}
	
	public DRGs getDRGs(String drgCode, String verCode) {
		StringBuilder sql = new StringBuilder("select _DRGs from DRGs _DRGs where drgCode='"+drgCode+"' and verCode='"+verCode+"' ");
		return (DRGs) getQueryChannelService().createJpqlQuery(sql.toString()).singleResult();
	}
	
	public void creatDRGs(DRGs dRGs) {
		dRGs.save();
	}
	
	public void updateDRGs(DRGs dRGs) {
		dRGs .save();
	}
	
	public void removeDRGs(DRGs dRGs) {
		if(dRGs != null){
			dRGs.remove();
		}
	}
	
	public void removeDRGss(Set<DRGs> dRGss) {
		for (DRGs dRGs : dRGss) {
			dRGs.remove();
		}
	}
	
	public List<DRGs> findAllDRGs(DRGs drgs) {
		StringBuilder jpql = new StringBuilder("SELECT _drgs FROM DRGs _drgs ");
		if (drgs.getVerCode()!=null && !"".equals(drgs.getVerCode())) {
			jpql.append(" where _drgs.verCode = '"+drgs.getVerCode()+"'");
		}
		List<DRGs> mrList = getQueryChannelService().createJpqlQuery(jpql.toString()).list();
		return mrList;
	}

	@Override
	public List<Map<String,Object>> findDrgsByPar(IndexCal indexCal) {
		String dateFrom = indexCal.getDateFrom();
		String dateTo = indexCal.getDateTo();
		String hospCode = indexCal.getHospCode();
		String verRegion = indexCal.getVerRegion();
		String mdcCode = indexCal.getParmdcCode();

		String sql = " select distinct pd.pardrg_code drgCode,drg.drg_desc drgDesc from drgs.t_patientdrg pd \n";
		sql += " left join drgs.mr_ipinfo ip on pd.parid=ip.pmainindex \n";
		sql += " left join drgs.mr_baseinfo base on pd.parid=base.pmainindex \n";
		sql += " left join drgs.t_drgs drg on pd.pardrg_code=drg.drg_code and pd.ver_code=drg.ver_code \n";
		sql += " where  to_char(ip.p00290000,'yyyy-mm') between '"+dateFrom+"' and '"+dateTo+"' \n";
		sql += " and instr('"+hospCode+"',base.p00010001)>0 and pd.ver_region='"+verRegion+"' \n";
		if(StringUtils.hasLength(mdcCode)){
			sql += " and pd.mdc='"+mdcCode+"' \n";
		}
		sql += " order by drgCode \n";
		List<Map<String,Object>> mrList = jdbcTemplateObj.queryForList(sql);
		return mrList;
	}
	
	@Override
	public List<Map<String, Object>> findDRGInfo(String asId, String verCode){
		String sql = "select a.drg_code, a.drg_desc, b.as_weight, b.as_risk_level from drgs.t_drgs a\n" +
					 "left join drgs.t_annualstd b\n" + 
					 "on a.drg_code=b.as_drg_code\n" + 
					 "where a.ver_code='"+verCode+"'\n" + 
					 "and b.as_id='"+asId+"'";
		List<Map<String, Object>> drgList = jdbcTemplateObj.queryForList(sql);
		return drgList;
	}

	@Override
	public List<IndexCal> findDrgsByDep(IndexCal IndexCal, String ratio) {
		double ratioD = 80;
		if(StringUtils.hasLength(ratio)){
			ratioD = Double.parseDouble(ratio)/100;
		}
		List<IndexCal> resultList = new LinkedList<IndexCal>();
		String depCode = IndexCal.getPardepCode();
		String depGroupCode = IndexCal.getPardepgroupCode();
		// 注释报错
//		String mrStdType = IndexCal.getMrStdtype();
//		String mrLot =  IndexCal.getMrLot();
		StringBuilder jpql = new StringBuilder();
		jpql.append(" select quotaDtl.parmrId from QuotaDtl quotaDtl \n ");
		jpql.append(" where quotaDtl.parquotaCode='TotalCaseCnt' \n ");
		jpql.append(" and exists( \n ");
		jpql.append(" select 1 from IndexCal IndexCal1 where 1=1 \n ");
		if(MonitorResultUtil.hasLength(depCode)){
			jpql.append(" and IndexCal1.pardepCode='"+depCode+"' \n ");
			jpql.append(" and IndexCal1.pardepgroupCode='DRG_DHCC' \n ");
		}
		if(MonitorResultUtil.hasLength(depGroupCode)){
			jpql.append(" and IndexCal1.pardepCode='DRG_DHCC' \n ");
			jpql.append(" and IndexCal1.pardepgroupCode='"+depGroupCode+"' \n ");
		}
		jpql.append(" and IndexCal1.pargroupName='DRG_DHCC' \n ");
		jpql.append(" and IndexCal1.parmdcCode='DRG_DHCC' \n ");
		jpql.append(" and IndexCal1.paradrgCode='DRG_DHCC' \n ");
		jpql.append(" and IndexCal1.pardrgCode<>'DRG_DHCC' \n ");
		// 注释报错
//		jpql.append(" and IndexCal1.mrLot='"+mrLot+"' \n ");
//		jpql.append(" and IndexCal1.mrStdtype='"+mrStdType+"' \n ");
		jpql.append(" and quotaDtl.parmrId=IndexCal1.mrId \n ");
		jpql.append(" ) \n ");
		jpql.append(" order by quotaDtl.quotaDetail desc \n ");
		List<String> list = getQueryChannelService().createJpqlQuery(jpql.toString()).list();
		
		//获取重点病种
		for(int i=0; i<list.size()*ratioD; i++){/*
			String mrId = list.get(i).toString();
//			System.out.println(mrId);
			String jpqls = "select IndexCal from IndexCal IndexCal where IndexCal.mrId='"+mrId+"' ";
			IndexCal result = (IndexCal) getQueryChannelService().createJpqlQuery(jpqls).singleResult();
			String jpqldtl = "select quotaDtl from QuotaDtl quotaDtl where quotaDtl.parmrId='"+mrId+"' ";
			List<QuotaDtl> dtlList = getQueryChannelService().createJpqlQuery(jpqldtl).list();
			result.setQuotaList(dtlList);
			resultList.add(result);
		*/}
		return resultList;
	}
	
	@Override
	public void update(DRGs drgs) {
		String sql2="update DRGS.T_DRGS d set d.drg_desc='"+drgs.getDrgDesc()+"' , d.adrg_code='"+drgs.getAdrgCode()+"' , d.ver_code='"+drgs.getVerCode()+"' where d.drg_code='"+drgs.getDrgCode()+"'";
		getQueryChannelService().createSqlQuery(sql2);
	}

	
	@Override
	public List<DRGs> findKeyDrgs(IndexCal queryVo) {
		String pType = "0";
		if(StringUtils.hasLength(queryVo.getpType())){
			pType = queryVo.getpType();
		}
		StringBuilder jpql = new StringBuilder("SELECT _drgs FROM DRGs _drgs WHERE EXISTS( SELECT 1 FROM ArchiveData _archiveData WHERE  _archiveData.adDrgcode=_drgs.drgCode");
		if (queryVo.getPardepgroupCode() != null
				&& !"".equals(queryVo.getPardepgroupCode())) {
			jpql.append(" and _archiveData.adDepgroupcode ='"+queryVo.getPardepgroupCode()+"'");
		}
		if (queryVo.getPardepCode() != null
				&& !"".equals(queryVo.getPardepCode())) {
			jpql.append(" and _archiveData.adDepcode ='"+queryVo.getPardepCode()+"'");
		}
		if (queryVo.getPargroupName() != null
				&& !"".equals(queryVo.getPargroupName())) {
			jpql.append(" and _archiveData.adGroupname ='"+queryVo.getPargroupName()+"'");
		}
		if (queryVo.getPardrgCode() != null
				&& !"".equals(queryVo.getParmdcCode())) {
			jpql.append(" and _archiveData.adMdccode ='"+queryVo.getPardrgCode()+"'");
		}
		// 注释报错
//		if (queryVo.getMrLot() != null
//				&& !"".equals(queryVo.getMrLot())) {
//			jpql.append(" and _archiveData.adLot ='"+queryVo.getMrLot()+"'");
//		}
		jpql.append(" and _archiveData.adAdrgcode ='DRG_DHCC'");
		jpql.append(" ) ");
		if(StringUtils.hasLength(queryVo.getParadrgCode()) && !"DRG_DHCC".equals(queryVo.getParadrgCode())){
			jpql.append("   AND   _drgs.adrgCode='"+queryVo.getParadrgCode()+"' ");
		}
		
		List<DRGs> mrList = getQueryChannelService()
				   .createJpqlQuery(jpql.toString())
				   .list();
		if(mrList.size()>0){
			return mrList;
		}else{
			jpql = new StringBuilder("SELECT _drgs FROM DRGs _drgs WHERE EXISTS( SELECT 1 FROM IndexCal _IndexCal WHERE  _IndexCal.pardrgCode=_drgs.drgCode and _IndexCal.verCode=_drgs.verCode ");
			if (queryVo.getPardepgroupCode() != null
					&& !"".equals(queryVo.getPardepgroupCode())) {
				jpql.append(" and _IndexCal.pardepgroupCode ='"+queryVo.getPardepgroupCode()+"'");
			}
			if (queryVo.getPardepCode() != null
					&& !"".equals(queryVo.getPardepCode())) {
				jpql.append(" and _IndexCal.pardepCode ='"+queryVo.getPardepCode()+"'");
			}
			if (queryVo.getPargroupName() != null
					&& !"".equals(queryVo.getPargroupName())) {
				jpql.append(" and _IndexCal.pargroupName ='"+queryVo.getPargroupName()+"'");
			}
			if (queryVo.getPardrgCode() != null
					&& !"".equals(queryVo.getParmdcCode())) {
				jpql.append(" and _IndexCal.parmdcCode ='"+queryVo.getPardrgCode()+"'");
			}
			if (queryVo.getParwardCode() != null
					&& !"".equals(queryVo.getParwardCode())) {
				jpql.append(" and _IndexCal.parwardCode ='"+queryVo.getParwardCode()+"'");
			}
			if (queryVo.getResident() != null
					&& !"".equals(queryVo.getResident())) {
				jpql.append(" and _IndexCal.resident ='"+queryVo.getResident()+"'");
			}
			if (queryVo.getProtomedicus() != null
					&& !"".equals(queryVo.getProtomedicus())) {
				jpql.append(" and _IndexCal.protomedicus ='"+queryVo.getProtomedicus()+"'");
			}
			// 注释报错
//			if (queryVo.getMrLot() != null
//					&& !"".equals(queryVo.getMrLot())) {
//				jpql.append(" and _IndexCal.mrLot ='"+queryVo.getMrLot()+"'");
//			}
//			if (queryVo.getMrStdtype() != null
//					&& !"".equals(queryVo.getMrStdtype())) {
//				if("month".equals(queryVo.getMrStdtype())){
//		   			jpql.append(" and _IndexCal.mrStdtype = 'period'");
//		   		}else{
//		   			jpql.append(" and _IndexCal.mrStdtype = 'year'");
//		   		}
//			}
			jpql.append(" and _IndexCal.pType ='"+pType+"'");
			jpql.append(" and _IndexCal.paradrgCode ='DRG_DHCC'");
			jpql.append(" )    ");
			if(StringUtils.hasLength(queryVo.getParadrgCode()) && !"DRG_DHCC".equals(queryVo.getParadrgCode())){
				jpql.append(" AND _drgs.adrgCode='"+queryVo.getParadrgCode()+"' ");
			}
			
			mrList = getQueryChannelService()
					   .createJpqlQuery(jpql.toString())
					   .list();
		}
		return mrList;
	}

	/**
	 * @method		:getDRGsDesc
	 * @description	:获取DRG描述
	 * @author		:fulianxia
	 * @date		:2016年1月7日
	 * @version     :2.0
	 * @copyright   :DHCC 2013-2015 
	 */
	@Override
	public String getDRGsDesc(String drgCode) {
		StringBuilder sql = new StringBuilder("select t.drg_desc from DRGs.T_DRGS t where t.drg_code='"+drgCode+"' and t.ver_code not like '%CC' order by ver_code desc");
		List<Object> result = getQueryChannelService().createSqlQuery(sql.toString()).list();
		if(result.size()>0){
			return  (String)result.get(0);
		}
		return  "";
	}
	
	/**
	 * 获取drg信息
	 */
	@Override
	public List<Map<String, Object>> findDrgInfoByYear(String groupVerCode) {
		return jdbcTemplateObj.queryForList("select * from drgs.t_annualstd a where a.ver_Code='"+groupVerCode+"' ");
	}
	
}
